<template>
  <div class="main-container">
    <!-- 顶部功能区 -->
    <div id="top" class="top-container">
      <!-- 图表容器 -->
      <div class="chart-container" v-show="advanceCharts">
        <!-- 现役区块 -->
        <div class="audit-count-card" @mouseover="showTooltip" @mouseleave="hideTooltip">
          <div class="count-header">
            <img src="../../assets/icons/Army.svg" alt="icon" style="width: 24px; height: 24px; margin-right: 8px;" />
            <span class="count-title">预储备成员总数</span>
          </div>
          <div class="count-content">
            <span class="highlight-number">{{ preReserveCount }}</span>
            <span class="unit">人</span>
          </div>
          <div class="tooltip" v-if="tooltipVisible">
            预储人数: {{ preReserveCount }}
          </div>
        </div>
        <!-- 图表 -->
        <div class="chart" ref="chart"></div>
      </div>

      <!-- 搜索容器 -->
      <div class="search-container">
        <!-- 姓名、学号、学院 -->
        <label for="qName" class="left-align">姓 名：</label>
        <input id="qName" type="text" v-model="qName" placeholder="请输入姓名" class="input-field">

        <label for="qStudentId" class="left-align">学 号：</label>
        <input id="qStudentId" type="text" v-model="qStudentId" placeholder="请输入学号" class="input-field">

        <label for="qCollege" class="left-align">学 院：</label>
        <input id="qCollege" type="text" v-model="qCollege" placeholder="请输入学院" class="input-field">

        <!-- 性别下拉选择框 -->
        <label for="qGender" class="left-align">性 别：</label>
        <select id="qGender" v-model="qGender" class="input-field">
          <option value="">请选择</option>
          <option value="1">男</option>
          <option value="0">女</option>
        </select>

        <!-- 搜索按钮 -->
        <el-button type="primary" :loading='isSearchLoding' @click="conditionPageQuery(currentPage, pageSize)"
          class="search-btn">
          <el-icon>
            <Search />
          </el-icon>搜索
        </el-button>

        <el-button style="width: 70px;border-radius: 4px;" type="danger" @click="onClear">
          <img src="../../assets/icons/clear.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 6px;" />
          清空
        </el-button>
      </div>


      <!-- 详细筛选 -->
      <div v-if="advancedSearch" class="advanced-search">
        <div class="search-container">
          <!-- 民族 -->
          <label for="qNationality" class="left-align">民 族：</label>
          <input id="qNationality" type="text" v-model="qNationality" placeholder="请输入民族" class="input-field">

          <!-- 专业 -->
          <label for="qMajor" class="left-align">专 业：</label>
          <input id="qMajor" type="text" v-model="qMajor" placeholder="请输入专业" class="input-field">

          <!-- 年级 -->
          <label for="qGrade" class="left-align">年 级：</label>
          <input id="qGrade" type="text" v-model="qGrade" placeholder="请输入年级" class="input-field">

          <!-- 政治面貌 -->
          <label for="qPoliticalAffiliation" class="left-align">政治面貌：</label>
          <select id="qPoliticalAffiliation" v-model="qPoliticalAffiliation" class="input-field">
            <option value="">请选择</option>
            <option value="群众">群众</option>
            <option value="共青团员">共青团员</option>
            <option value="中共党员">中共党员</option>
            <option value="中共预备党员">中共预备党员</option>
          </select>

          <!-- 身高区间 -->
          <div style="gap:200px">
            <label for="qHeightMin" style="margin-right: 10px;" class="left-align">身高区间：</label>
            <select id="qHeightMin" v-model="qHeightMin" class="input-field">
              <option value="">最小身高</option>
              <option value="150">150cm</option>
              <option value="155">155cm</option>
              <option value="160">160cm</option>
              <option value="165">165cm</option>
              <option value="170">170cm</option>
              <option value="175">175cm</option>
              <option value="180">180cm</option>
            </select>
            <select id="qHeightMax" v-model="qHeightMax" class="input-field">
              <option value="">最大身高</option>
              <option value="170">170cm</option>
              <option value="175">175cm</option>
              <option value="180">180cm</option>
              <option value="185">185cm</option>
              <option value="190">190cm</option>
              <option value="195">195cm</option>
              <option value="200">200cm</option>
            </select>
          </div>

          <!-- 年龄区间 -->
          <div style="gap:200px">
            <label for="qAgeMin" style="margin-right: 10px;" class="left-align">年龄区间：</label>
            <select id="qAgeMin" v-model="qAgeMin" class="input-field">
              <option value="">最小年龄</option>
              <option value="18">18</option>
              <option value="19">19</option>
              <option value="20">20</option>
              <option value="21">21</option>
              <option value="22">22</option>
              <option value="23">23</option>
              <option value="23">24</option>
            </select>
            <select id="qAgeMax" v-model="qAgeMax" class="input-field">
              <option value="">最大年龄</option>
              <option value="18">18</option>
              <option value="19">19</option>
              <option value="20">20</option>
              <option value="21">21</option>
              <option value="22">22</option>
              <option value="23">24</option>
            </select>
          </div>

          <!-- 视力 -->
          <label for="qVision" class="left-align">视力：</label>
          <select id="qVision" v-model="qVision" class="input-field">
            <option value="">请选择视力(大于等于)</option>
            <option value="4.4">4.4</option>
            <option value="4.6">4.6</option>
            <option value="4.8">4.8</option>
            <option value="5.0">5.0</option>
          </select>

          <!-- 体重区间 -->
          <div style="gap:200px">
            <label for="qWeightMin" style="margin-right: 10px;" class="left-align">体重区间：</label>
            <select id="qWeightMin" v-model="qWeightMin" class="input-field">
              <option value="">最小体重</option>
              <option value="40">40kg</option>
              <option value="45">45kg</option>
              <option value="50">50kg</option>
              <option value="55">55kg</option>
              <option value="60">60kg</option>
              <option value="65">65kg</option>
              <option value="70">70kg</option>
            </select>
            <select id="qWeightMax" v-model="qWeightMax" class="input-field">
              <option value="">最大体重</option>
              <option value="50">50kg</option>
              <option value="55">55kg</option>
              <option value="60">60kg</option>
              <option value="65">65kg</option>
              <option value="70">70kg</option>
              <option value="75">75kg</option>
              <option value="80">80kg</option>
            </select>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细筛选按钮 -->
    <div class="advanced-btn-container">
      <button @click="toggleAdvancedSearch" class="secondary-btn">
        {{ advancedSearch ? '收起筛选' : '展开筛选' }}
      </button>
      <button @click="toggleAdvancedCharts" class="secondary-btn">
        {{ advanceCharts ? '收起图表' : '展开图表' }}
      </button>
    </div>

    <!-- 表格列选择下拉框 -->
    <div class="column-selector">
      <div class="selectorTitle">呈现列：</div>
      <el-select v-model="selectedColumns" multiple placeholder="请选择要显示的列" @change="handleColumnChange">
        <el-option v-for="column in columnOptions" :key="column.value" :label="column.label" :value="column.value" />
      </el-select>

      <!-- 导出勾选按钮 -->
      <div class="export-btn-container">
        <!-- 导出按钮 -->
        <div class="export-btn-container">
          <el-button type="primary" @click="exportSelecteList" style="width: 120px;;">
            <img src="../../assets/icons/List.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
            导出为列表
          </el-button>
          <el-button @click="exportSelectExcel" style="width: 120px;background-color:forestgreen;color: aliceblue;">
            <img src="../../assets/icons/Excel.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
            导出为Excel
          </el-button>
          <el-button @click="exportSelectPDF" style="width: 120px;background-color: brown;color: aliceblue;">
            <img src="../../assets/icons/PDF图标.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
            导出为PDF
          </el-button>
        </div>
      </div>
    </div>

    <!-- 表格展示区 -->
    <el-table :data="tableData" row-key="studentId" max-height="670" style="width: 100%;"
      @selection-change="handleSelectionChange" :header-cell-style="{ background: '#eef1f6', color: '#2c2c3b' }"
      :scroll-x="true">
      <el-table-column type="selection" min-width="30"></el-table-column>
      <el-table-column label="序号" align="center" fixed min-width="60">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="studentId" label="学号" align="center" v-if="selectedColumns.includes('studentId')"
        min-width="180" />
      <el-table-column prop="name" label="姓名" fixed align="center" v-if="selectedColumns.includes('name')"
        min-width="80" />
      <el-table-column label="性别" align="center" v-if="selectedColumns.includes('gender')" min-width="60">
        <template #default="scope">
          {{ scope.row.gender === "1" ? '男' : scope.row.gender === "0" ? '女' : '未知' }}
        </template>
      </el-table-column>
      <el-table-column prop="birthDate" label="出生日期" sortable align="center"
        v-if="selectedColumns.includes('birthDate')" min-width="120" />
      <el-table-column prop="college" label="学院" align="center" v-if="selectedColumns.includes('college')"
        min-width="200" />
      <el-table-column prop="className" label="班级" align="center" v-if="selectedColumns.includes('className')"
        min-width="200" />
      <el-table-column prop="politicalAffiliation" label="政治面貌" align="center"
        v-if="selectedColumns.includes('politicalAffiliation')" :min-width="120" />
      <el-table-column prop="nationality" label="民族" align="center" v-if="selectedColumns.includes('nationality')"
        min-width="60" />
      <el-table-column prop="major" label="专业" align="center" v-if="selectedColumns.includes('major')"
        min-width="160" />
      <el-table-column prop="telephone" label="电话" align="center" v-if="selectedColumns.includes('telephone')"
        min-width="130" />
      <el-table-column prop="height" label="身高" align="center" v-if="selectedColumns.includes('height')"
        min-width="80" />
      <el-table-column prop="weight" label="体重" align="center" v-if="selectedColumns.includes('weight')"
        min-width="80" />
      <el-table-column prop="vision" label="视力" align="center" v-if="selectedColumns.includes('vision')"
        min-width="80" />
      <el-table-column label="操作" align="center" fixed="right" min-width="130">
        <template #default="scope">
          <router-link :to="{ path: '/admin/preReserve/personalInfo', query: { studentId: scope.row.studentId } }"
            class="detail-btn">查看详细信息</router-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部分页导航栏 -->
    <div class="page-nav">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" hide-on-single-page="true"
        layout="total, prev, pager, next, sizes" background :page-sizes="[5, 10, 20, 50]" :size="size" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { RouterLink, useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { getChartData, getPreCount, getPage, getMemberList, getExcle, getPdf } from '@/api/pre-reserve/pre-reserve-member';


// 分页相关数据
const size = ref('default');
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

//更多筛选项
const isSearchLoding = ref(false);

// 表格展示数据
let tableData = ref([]);
// 预储总人数
const preReserveCount = ref(0);

//鼠标悬浮显示预储人数
const tooltipVisible = ref<boolean>(false);

// 方框展示区的交互
const showTooltip = () => {
  tooltipVisible.value = true;
};
const hideTooltip = () => {
  tooltipVisible.value = false;
}



// 查询参数定义
const qName = ref('');
const qStudentId = ref("");
const qCollege = ref("");
const qGender = ref("");
const qPoliticalAffiliation = ref("");
const qAgeMin = ref("");
const qAgeMax = ref("");
const qNationality = ref("");
const qGrade = ref("");
const qMajor = ref("");
const qHeightMin = ref("");  // 身高最小值
const qHeightMax = ref("");  // 身高最大值
const qWeightMin = ref("");  // 体重最小值
const qWeightMax = ref("");  // 体重最大值
const qVision = ref("");  // 视力

// 选中的成员信息
const selectedMembers = ref([]);

// 显示详细筛选项
const advancedSearch = ref(false);
//图表
const advanceCharts = ref(true);


const router = useRouter()
const route = useRoute()
// 从URL参数初始化表单
const initFromUrl = () => {
  qName.value = route.query.name || ''
  qStudentId.value = route.query.studentId || ''
  qCollege.value = route.query.college || ''
  qGender.value = route.query.gender || ''
  qAgeMax.value = route.query.ageMax || ''
  qAgeMin.value = route.query.ageMin || ''

  // 分页参数
  if (route.query.page) currentPage.value = parseInt(route.query.page)
  if (route.query.pageSize) pageSize.value = parseInt(route.query.pageSize)
}
// 更新URL参数
const updateUrlParams = () => {
  const queryParams: Record<string, string | number> = {};

  // 只添加有值的参数
  if (qName.value) queryParams.name = qName.value
  if (qStudentId.value) queryParams.studentId = qStudentId.value
  if (qCollege.value) queryParams.college = qCollege.value
  if (qGender.value) queryParams.gender = qGender.value
  if (qAgeMin.value) queryParams.ageMin = qAgeMin.value
  if (qAgeMax.value) queryParams.ageMax = qAgeMax.value
  // 添加分页参数
  queryParams.page = currentPage.value
  queryParams.pageSize = pageSize.value

  // 更新URL而不刷新页面
  router.push({
    query: queryParams
  })
}



// 表格列选择相关
const columnOptions = ref([
  { label: '学号', value: 'studentId' },
  { label: '姓名', value: 'name' },
  { label: '性别', value: 'gender' },
  { label: '出生日期', value: 'birthDate' },
  { label: '学院', value: 'college' },
  { label: '班级', value: 'className' },
  { label: '政治面貌', value: 'politicalAffiliation' },
  { label: '民族', value: 'nationality' },
  { label: '专业', value: 'major' },
  { label: '电话', value: 'telephone' },
  { label: '身高', value: 'height' },
  { label: '体重', value: 'weight' },
  { label: '视力', value: 'vision' },
]);

const selectedColumns = ref(['name', 'telephone', 'gender', 'birthDate', 'college', 'politicalAffiliation', 'nationality']);

//清空搜索项
function onClear() {
  qName.value = '',
    qStudentId.value = '',
    qCollege.value = '',
    qGender.value = '',
    qPoliticalAffiliation.value = '',
    qAgeMin.value = '',
    qAgeMax.value = '',
    qNationality.value = '',
    qGrade.value = '',
    qMajor.value = '',
    qHeightMin.value = '',
    qHeightMax.value = '',
    qWeightMin.value = '',
    qWeightMax.value = '',
    qVision.value = ''
}


// 组件实例挂载完成之后 调用函数获取相关数据
onMounted(() => {
  initFromUrl()
  conditionPageQuery(currentPage.value, pageSize.value);
  initChart();
  getPreReserveCount();
});

// 多选框 选择项发生变化时触发
function handleSelectionChange(selection) {
  selectedMembers.value = selection.map(item => item.studentId);
}

//饼图
const chart = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
const initChart = () => {
  if (chart.value) {
    chartInstance = echarts.init(chart.value);
    updateChart();
  }
}
const updateChart = async () => {
  try {
    type EChartsOption = echarts.EChartsOption;
    var option: EChartsOption;
    const response = await getChartData('college');

    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      series: [
        {
          name: '姓名',
          type: 'pie',
          radius: '80%',
          data: response.data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    option && chartInstance.setOption(option);
  } catch (error) {
    console.log("饼图获取数据失败！")
  }
}


//预储人数获取
function getPreReserveCount() {
  getPreCount().then(response => {
    preReserveCount.value = response.data;
  }).catch(error => {
    ElMessage.error('预储人数获取失败！');
    console.log(error);
  })
}

// 条件分页查询获取所有的成员
function conditionPageQuery(page, pageSize) {
  isSearchLoding.value = true;

  // 先更新URL参数
  updateUrlParams()
  const params = {
    page,
    pageSize,
    name: qName.value,
    studentId: qStudentId.value,
    college: qCollege.value,
    gender: qGender.value,
    politicalAffiliation: qPoliticalAffiliation.value,
    ageMin: qAgeMin.value, // 年龄最小值
    ageMax: qAgeMax.value, // 年龄最大值
    nationality: qNationality.value,
    grade: qGrade.value,
    major: qMajor.value,
    heightMin: qHeightMin.value,  // 身高最小值
    heightMax: qHeightMax.value,  // 身高最大值
    weightMin: qWeightMin.value,  // 体重最小值
    weightMax: qWeightMax.value,  // 体重最大值
    vision: qVision.value         // 视力
  }


  getPage(params).then(result => {
    tableData.value = result.data.records;
    total.value = result.data.total;
    isSearchLoding.value = false;
  });
}

// 切换详细筛选显示
function toggleAdvancedSearch() {
  advancedSearch.value = !advancedSearch.value;
  if (!advancedSearch.value) {
    // 清空输入框内容
    qPoliticalAffiliation.value = "";
    qAgeMin.value = "";
    qAgeMax.value = "";
    qNationality.value = "";
    qGrade.value = "";
    qHeightMin.value = "";
    qHeightMax.value = "";
    qWeightMin.value = "";
    qWeightMax.value = "";
    qVision.value = "";
  }
}
//折叠图表
function toggleAdvancedCharts() {
  advanceCharts.value = !advanceCharts.value;
}

// 每页显示条目个数变化
const handleSizeChange = (val) => {
  conditionPageQuery(currentPage.value, val);
};

// 当前页码变化
const handleCurrentChange = (val) => {
  conditionPageQuery(val, pageSize.value);
};

// 处理列选择变化
function handleColumnChange() {
  // 这里可以根据需要添加逻辑
}


// 处理导出命令
// 导出为列表
function exportSelecteList() {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请先选择要导出的成员');
    return;
  }
  ElMessage.success("正在导出，请稍等！");
  const data = {
    heads: selectedColumns.value,
    studentIds: selectedMembers.value
  }
  getMemberList(data);
}

// 导出为Excel
function exportSelectExcel() {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请先选择要导出的成员');
    return;
  }
  ElMessage.success("正在导出，请稍等！");
  const data = {
    studentIds: selectedMembers.value
  }
  getExcle(data);
}

// 导出为PDF
function exportSelectPDF() {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请先选择要导出的成员');
    return;
  }
  ElMessage.success("正在导出，请稍等！");
  const data = {
    studentIds: selectedMembers.value
  };
  getPdf(data);
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}

/* 新增：外层容器样式 */
.main-container {
  width: 100%;
  height: 100%;
  /* min-width: 1492px; */
}

/* 数据卡片样式 */
.audit-count-card {
  min-width: 240px;
  padding: 40px;
  background: linear-gradient(135deg, #ffffff 0%, #f1f3f5 100%);
  border-radius: 12px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 水平居中 */
  justify-content: center;
  /* 垂直居中 */
  position: relative;
  /* 为了悬浮提示 */
}

.audit-count-card:hover {
  transform: translateY(-2px);
}



/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

/* 标题样式 */
.count-header {
  display: flex;
  align-items: center;
  justify-content: center;
  /* 水平居中 */
  gap: 8px;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 1px solid #dee2e6;
}

.count-title {
  font-size: 1.1em;
  color: #495057;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 数字展示 */
.count-content {
  text-align: center;
  margin: 20px 0;
}

.highlight-number {
  font-size: 2.8em;
  font-weight: 700;
  color: #f03e3e;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  margin-right: 5px;
}

.unit {
  font-size: 1.2em;
  color: #868e96;
  vertical-align: super;
}

/* 图表容器 */
.chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}

.tooltip {
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #333;
  color: #fff;
  padding: 5px;
  border-radius: 4px;
  font-size: 12px;
}

.chart {
  width: 600px;
  height: 300px;
  border-radius: 8px;
}

/* 顶部功能区 */
#top {
  max-width: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

/* 搜索容器 */
.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  min-width: 1430px;
}

/* 输入框 */
.input-field {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  width: 160px;
  background-color: #fff;
  color: #333;
}

.input-field:focus {
  border-color: #409eff;
  outline: none;
}

/* 标签 */
.left-align {
  width: 80px;
  text-align: center;
  color: #606266;
}

/* 搜索按钮 */
.search-btn {
  width: 70px;
  padding: 8px 16px;
  font-size: 14px;
  background-color: #4caf50;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
}

.search-btn:hover {
  background-color: #45a049;
}


/* 详细筛选按钮 */
.secondary-btn {
  margin-right: 10px;
  padding: 8px 16px;
  font-size: 14px;
  background-color: #e4e7ed;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.secondary-btn:hover {
  background-color: #d9e4f5;
}

/* 高级筛选按钮容器 */
.advanced-btn-container {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

/* 高级筛选区域 */
.advanced-search {
  margin-top: 20px;
}

.advanced-search .search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

/* 分页导航栏 */
.page-nav {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

/* 操作按钮 */
.detail-btn {
  text-decoration: none;
  color: inherit;
  border: none;
  background: none;
  padding: 0;
  font: inherit;
  cursor: pointer;
  outline: none;
  background-color: #409eff;
  color: white;
  padding: 6px 16px;
  text-align: center;
  display: inline-block;
  font-size: 12px;
  border-radius: 5px;
}

.detail-btn:hover {
  background-color: #66b1ff;
}

/* 导出按钮容器 */
.export-btn-container {
  display: flex;
  justify-content: flex-end;
  margin-left: 20px;
}

/* 表格样式 */
.el-table {
  margin-top: 10px;
  background-color: #fff;
  border-radius: 8px;
  /* box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);阴影 */
}

.el-table th {
  background-color: #f8f9fa;
  color: #333;
}

.el-table td {
  color: #606266;
}

/* 列选择器 */
.column-selector {
  display: flex;
  width: 80%;
  margin: auto;
  align-items: center;
  margin-bottom: 5px;
}

.selectorTitle {
  width: 110px;
  color: #606266;
}
</style>

<style>
.el-table .cell {
  line-height: 17px;
}
</style>